<template>
  <n-scrollbar x-scrollable style="max-height: 100vh">
  <CommonPage show-footer style="padding: 0px;background-color: white">
    <div class="w-full f-c-c" style="background-color: white;">
      <div style="margin-top: 0px" class="max-w-900 w-full">
        <div style="margin-left: -135px">
        </div>
          <n-form ref="formRef"
                  :model="formValue"
                  :rules="formRules"
                  class="mt-20 flex flex-col px-15"
                  label-placement="left"
                  label-align="right"
                  label-width="200px"
          >
            <div class="grid md:gap-x-30">
                <n-form-item label="姓名" path="name">
                <n-input
                        v-model:value="formValue.name"
                        @blur="findExistUser"
                        placeholder="请输入姓名"
                ></n-input>
            </n-form-item>
              <n-form-item label="用户名" path="username">
                <n-input
                    v-model:value="formValue.username"

                    placeholder="请输入人用户名"

                />
              </n-form-item>

              <n-form-item label="密码" path="password">
                <n-input
                    v-model:value="formValue.password"
                    placeholder="请输入密码"
                    type="password"
                >
                </n-input>
<!--                @blur="findExistUser"-->
              </n-form-item>
                <n-form-item label="确认密码" path="confirmPassword">
                    <n-input
                            v-model:value="formValue.confirmPassword"
                            placeholder="请确认密码"
                            type="password"
                    >
                    </n-input>
                    <!--                @blur="findExistUser"-->
                </n-form-item>
              <n-form-item label="角色" path="role">
                <n-select
                        v-model：value="formValue.role"
                        filterable
                        placeholder="请选择角色"
                        :options="options"

                >
                </n-select>
              </n-form-item>

              <n-form-item label="电话" path="phone">
                <n-input
                    v-model:value="formValue.phone"
                    placeholder="请输入电话号码"
                ></n-input>
              </n-form-item>
                <n-form-item label="邮箱" path="email">
                    <n-input v-model:value="formValue.email" placeholder="请输入邮箱"></n-input>
                </n-form-item>

            </div>
              <br>
            <n-form-item>
              <n-button type="primary" @click="submitForm" style="margin-left: 43%" :loading="loading" :disabled="disable">注册</n-button>
              <n-button type="primary" @click="cancel" style="margin-left: 25px" >取消</n-button>
            </n-form-item>
          </n-form>
      </div>
    </div>
  </CommonPage>
  </n-scrollbar>
</template>

<script setup>
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import api from '@/api/admin'
import {confirmPasswordRule, emailRule, requiredRule, strictPasswordRule} from "@/utils/validator";
import sha256 from "crypto-js/sha256";
import {generateRandomString} from "@/utils";
const disable=ref(false)
const router = useRouter()
const { username } = history.state
const loading=ref(false)
const options=['SUPERADMIN','ADMIN'].map((v)=>({
    label:v,
    value:v
}))
const roleOptions=ref([])
const formRef = ref(null)
const formValue = ref({
  name: '',
  role:'请选择角色',
  username:'',
  email: '',
  password: '',
  confirmPassword: '',
  phone: '',
})

const formRules = {
    username: requiredRule('用户名'),
    name: requiredRule('姓名'),
    phone: requiredRule('电话'),
    email: emailRule(false),
    password: strictPasswordRule(),
    confirmPassword: confirmPasswordRule(formValue, 'password'),
    role:requiredRule('角色'),
}
const handleSearchRole=async (query)=>{

}

const findExistUser = async () => {
    const res = await api.findAdminuserByno({
      no: formValue.value.no,
      schoolId:formValue.value.schoolId
    })
    if (res.data) {
      const {name,username, email,phone} = res.data
      formValue.value.name = name
      formValue.value.username=username
      formValue.value.email = email
      formValue.value.phone=phone
      if (name) {
        disable.value=true
        $dialog.error({
          title: '注册失败',
          content: `你已经注册过一个用户，原来的用户名为：${username}，忘记密码请点击确认进入重置密码页面`,
          positiveText: '确认',
          negativeText: '取消',
          onPositiveClick: () => {
            router.push({ name: 're-pw-info', state: { name } })
          },
        })
      }
    }else {
      formValue.value.name = ''
      formValue.value.account = ''
      formValue.value.email = ''
      formValue.value.question = ''
      formValue.value.answer = ''
      disable.value = false
    }
}
const submitForm = () => {
  formRef.value.validate(async (errors) => {
    if (!errors) {
      try {
        loading.value = true
        $message.loading('处理中...')
        const payload = {
          ...formValue.value,
          password: sha256(formValue.value.password.trim()).toString(),
          sessionId: generateRandomString(64) + formValue.value.password.trim(), //应付检查的无用字段
        }
        delete payload.confirmPassword
        console.log(payload)
        await api.signTeacher(payload)
        if (formValue.value.role==='teacher'){
          $dialog.success({
            title: '教师注册信息提示',
            content: '恭喜您注册成功，请点击确定前往登录页面',
            positiveText: '确认',
            onPositiveClick: () => {
              router.push({ name: 'AdminLogin' })
            },
            closable: false,
            maskClosable: false,
          })
        }else {
          $dialog.success({
            title: '助教注册信息提示',
            content: '恭喜您注册成功，请点击确定前往登录页面',
            positiveText: '确认',
            onPositiveClick: () => {
              router.push({ name: 'AdminLogin' })
            },
            closable: false,
            maskClosable: false,
          })
        }

      } catch (err) {
        if (err.code === 40000) {
          const { account } = err.data
          $dialog.error({
            title: '注册失败',
            content: `你已经注册过一个用户，原来的用户名为：${account}，忘记密码请点击确认进入重置密码页面`,
            positiveText: '确认',
            negativeText: '取消',
            onPositiveClick: () => {
              router.push({ name: 'AdminRePwInfo', state: { account } })
            },
          })
        }
      } finally {
        loading.value = false
        $message.removeMessage()
      }
    } else {
      $message.error('表单验证失败')
    }
  })
}
const cancel=()=>{
  router.push({name:'AdminLogin'})
}

onMounted(() => {
  if (formValue.value.account) {
    formRef.value?.validate(
        (errors) => {
          if (errors) {
            console.error(errors)
          } else {
            console.log('yes')
          }
        },
        (rule) => {
          return rule?.key === 'account'
        }
    )
  }
})
</script>
